
const express = require('express');
const router = express.Router();
const db = require('../config/db');

router.post('/', async (req, res) => {
  const { name, content } = req.body;

  if (!name?.trim() || !content?.trim()) {
    return res.status(400).json({ error: '姓名和内容不能为空' });
  }

  if (name.length > 50 || content.length > 300) {
    return res.status(400).json({ error: '内容超出长度限制' });
  }

  try {
    await db.execute(
      'INSERT INTO wishes (name, content) VALUES (?, ?)',
      [name.trim(), content.trim()]
    );
    res.status(201).json({ message: '许愿成功！' });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

//查询最近十条数据
router.get('/',async(req,res)=>{
  try{
    const [rows]= await db.execute(
      "SELECT * FROM  wishes ORDER BY created_at DESC LIMIT 10 "
    );
    res.json(rows)
  }
  catch(err){
    res.status(500).json({error:err.message})
  }
})
module.exports = router;
